{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.4842105263157895\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "import os\n",
    "# 推文数据集\n",
    "data_file = \"./Data/python_tweets.json\"\n",
    "# 类别数据集\n",
    "class_file = \"./Data/python_classes.json\"\n",
    "\n",
    "data_list = []\n",
    "class_list = []\n",
    "\n",
    "# 加载推文\n",
    "with open(data_file) as f:\n",
    "    for line in f:\n",
    "        # 如果内容为空\n",
    "        if(len(line.strip()) == 0):\n",
    "            continue\n",
    "        data_list.append(json.loads(line)[\"text\"])\n",
    "# 加载类别\n",
    "with open(class_file) as f:\n",
    "     class_list = json.loads(f.read())\n",
    "import numpy as np\n",
    "class_list = np.array(class_list)\n",
    "data_list = np.array(data_list)\n",
    "\n",
    "import numpy as np\n",
    "print(np.mean(class_list == 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.base  import TransformerMixin\n",
    "from nltk import word_tokenize\n",
    "class NLTKBOW(TransformerMixin):\n",
    "    def fit(self,X,y=None):\n",
    "        return self\n",
    "    def transform(self,X):\n",
    "#         words = []\n",
    "#         for document in X:\n",
    "#             words_dict = defaultdict(int)\n",
    "#             for word in word_tokenize(document):\n",
    "#                 words_dict[word] += 1\n",
    "#             words.append(words_dict)\n",
    "#         return words\n",
    "        return [\n",
    "            {\n",
    "                word:True for word in word_tokenize(document)\n",
    "            }for document in X\n",
    "        ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.feature_extraction import DictVectorizer\n",
    "from sklearn.naive_bayes import BernoulliNB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Pipeline] ............ (step 1 of 3) Processing 布袋模型转换, total=   0.0s\n",
      "[Pipeline] ........... (step 2 of 3) Processing 字典列表转矩阵, total=   0.0s\n",
      "[Pipeline] ........... (step 3 of 3) Processing 素贝叶斯分类器, total=   0.0s\n",
      "[Pipeline] ............ (step 1 of 3) Processing 布袋模型转换, total=   0.0s\n",
      "[Pipeline] ........... (step 2 of 3) Processing 字典列表转矩阵, total=   0.0s\n",
      "[Pipeline] ........... (step 3 of 3) Processing 素贝叶斯分类器, total=   0.0s\n",
      "[Pipeline] ............ (step 1 of 3) Processing 布袋模型转换, total=   0.0s\n",
      "[Pipeline] ........... (step 2 of 3) Processing 字典列表转矩阵, total=   0.0s\n",
      "[Pipeline] ........... (step 3 of 3) Processing 素贝叶斯分类器, total=   0.0s\n",
      "[Pipeline] ............ (step 1 of 3) Processing 布袋模型转换, total=   0.0s\n",
      "[Pipeline] ........... (step 2 of 3) Processing 字典列表转矩阵, total=   0.0s\n",
      "[Pipeline] ........... (step 3 of 3) Processing 素贝叶斯分类器, total=   0.0s\n",
      "[Pipeline] ............ (step 1 of 3) Processing 布袋模型转换, total=   0.0s\n",
      "[Pipeline] ........... (step 2 of 3) Processing 字典列表转矩阵, total=   0.0s\n",
      "[Pipeline] ........... (step 3 of 3) Processing 素贝叶斯分类器, total=   0.0s\n",
      "Score: 0.6210526315789473\n"
     ]
    }
   ],
   "source": [
    "#流水线\n",
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.model_selection import cross_val_score\n",
    "pipeline = Pipeline([('布袋模型转换',NLTKBOW()),\n",
    "                    ('字典列表转矩阵',DictVectorizer(sparse=True)),\n",
    "                    ('素贝叶斯分类器',BernoulliNB())],\n",
    "                    verbose=True\n",
    "                   )\n",
    "scores = cross_val_score(pipeline,data_list,class_list,scoring='accuracy')\n",
    "import numpy as np\n",
    "print(\"Score: {}\".format(np.mean(scores)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Pipeline] ............ (step 1 of 3) Processing 布袋模型转换, total=   0.0s\n",
      "[Pipeline] ........... (step 2 of 3) Processing 字典列表转矩阵, total=   0.0s\n",
      "[Pipeline] ........... (step 3 of 3) Processing 素贝叶斯分类器, total=   0.0s\n",
      "[Pipeline] ............ (step 1 of 3) Processing 布袋模型转换, total=   0.0s\n",
      "[Pipeline] ........... (step 2 of 3) Processing 字典列表转矩阵, total=   0.0s\n",
      "[Pipeline] ........... (step 3 of 3) Processing 素贝叶斯分类器, total=   0.0s\n",
      "[Pipeline] ............ (step 1 of 3) Processing 布袋模型转换, total=   0.0s\n",
      "[Pipeline] ........... (step 2 of 3) Processing 字典列表转矩阵, total=   0.0s\n",
      "[Pipeline] ........... (step 3 of 3) Processing 素贝叶斯分类器, total=   0.0s\n",
      "[Pipeline] ............ (step 1 of 3) Processing 布袋模型转换, total=   0.0s\n",
      "[Pipeline] ........... (step 2 of 3) Processing 字典列表转矩阵, total=   0.0s\n",
      "[Pipeline] ........... (step 3 of 3) Processing 素贝叶斯分类器, total=   0.0s\n",
      "[Pipeline] ............ (step 1 of 3) Processing 布袋模型转换, total=   0.0s\n",
      "[Pipeline] ........... (step 2 of 3) Processing 字典列表转矩阵, total=   0.0s\n",
      "[Pipeline] ........... (step 3 of 3) Processing 素贝叶斯分类器, total=   0.0s\n",
      "Score: 0.3715617715617715\n"
     ]
    }
   ],
   "source": [
    "#流水线\n",
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.model_selection import cross_val_score\n",
    "pipeline = Pipeline([('布袋模型转换',NLTKBOW()),\n",
    "                    ('字典列表转矩阵',DictVectorizer(sparse=True)),\n",
    "                    ('素贝叶斯分类器',BernoulliNB())],\n",
    "                    verbose=True\n",
    "                   )\n",
    "scores = cross_val_score(pipeline,data_list,class_list,scoring='f1')\n",
    "import numpy as np\n",
    "print(\"Score: {}\".format(np.mean(scores)))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
